<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-row type="flex" justify="end">
          <el-button type="primary" size="small" @click="addPermission('0',1)">添加权限</el-button>
        </el-row>
        <!--
          default-expand-all 默认全部展示
         -->
        <el-table :data="permissionList" row-key="id" default-expand-all>
          <el-table-column label="权限名称" prop="name" />
          <el-table-column label="权限标记" prop="code" />
          <el-table-column label="权限描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button v-if="row.type === 1" type="text" size="small" @click="addPermission(row.id,2)">新增子权限</el-button>
              <el-button type="text" size="small" @click="editPermission(row.id)">编辑权限</el-button>
              <el-button type="text" size="small" @click="delClick(row.id)">删除权限</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!-- 弹出层 -->
      <PermissionDialog ref="formData" :show-dialog.sync="showDialog" @updatePermission="updatePermissionFn" />
    </div>
  </div>
</template>

<script>
import PermissionDialog from './components/permission-dialog.vue'
import { listToTreeData } from '@/utils'
import { getPermissionList, delPermission } from '@/api/permission'
export default {
  components: { PermissionDialog },
  data() {
    return {
      permissionList: [], // 权限点列表
      showDialog: false
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    updatePermissionFn() {
      this.getPermissionList()
    },
    // 编辑
    editPermission(id) {
      this.$refs.formData.getPermissionById(id)
      this.showDialog = true
    },
    // 新增
    addPermission(pid, type) {
      // pid 是上一级部门id,type决定是否拥有权限(1为访问权限(这个作为父级,可以在添加一个子级),2为功能权限)
      this.$refs.formData.addPermission(pid, type)
      this.showDialog = true
    },
    // 删除
    async delClick(id) {
      await this.$confirm('你确定要删除吗?')
      await delPermission(id)
      this.$message.success('删除成功')
      this.getPermissionList()
    },
    async getPermissionList() {
      this.permissionList = listToTreeData(await getPermissionList(), '0')
    }
  }
}
</script>

<style>

</style>
